package com.lenovo.order_service.exception;

import com.lenovo.order_service.enums.ResultCode;
import com.lenovo.order_service.utils.BaseResponse;
import com.lenovo.order_service.utils.BaseResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    /**
     * 参数校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public BaseResponse methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        LOGGER.error("参数校验异常:{}, {}", ex.getMessage(), ex);
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(",");
        }
        String msg = sb.toString();
        return BaseResponseUtil.getErrorBaseResponse(ResultCode.REQUEST_PARAM_ERROR.getCode(), msg, null);
    }


    /**
     * SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler({SQLException.class})
    public BaseResponse sqlException(SQLException ex) {
        LOGGER.error("SQL异常:{}, {}", ex.getMessage(), ex);
        return BaseResponseUtil.getErrorBaseResponse(ResultCode.DATABASE_ERROR.getCode(), ResultCode.DATABASE_ERROR.getName(), null);
    }


    /**
     * Exception异常
     * @param ex
     * @return
     */
    @ExceptionHandler({Exception.class})
    public BaseResponse exception(Exception ex) {
        LOGGER.error("Exception异常:{}, {}", ex.getMessage(), ex);
        return BaseResponseUtil.getErrorBaseResponse(ResultCode.ERROR.getCode(), ResultCode.ERROR.getName(), null);
    }

    /**
     * 业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler({BusinessException.class})
    public BaseResponse baseServiceException(BusinessException ex) {
        LOGGER.error("业务处理异常:" + ex.getMessage(), ex);
        return BaseResponseUtil.getErrorBaseResponse(ex.getCode(), ex.getMessage(), null);
    }
}
